// const fs= require ('fs')
const path = require('path')
const express = require('express')
const app = express()

/* 全局解析 */
/* const bodyParser = require('body-parser')
app.use(bodyParser.json()) */

app.use(express.urlencoded({ extended: false }))
app.use(express.json())

app.use('/static', express.static(path.join(__dirname, '../static')))

/* 自定义中间件 */

// 可以用use/all来实现访问页面404处理
// 上面所有的请求如果都没有匹配成功，则*全部匹配成功
app.all('/demo/*', (req, res, next) => {
  // console.log(req)
  // req.testing = 'testing'
  // 在这里验证token
  console.log(new Date().toISOString(), ' ', 'Authorization:', req.get('Authorization'))
  console.log('res Content-Type:', req.get('Content-Type'))
  const token = req.get('Authorization')
  if (token === '111') {
    return next()
  } else {
    res.status(403)
    res.end()
  }
  // console.log(res.header('Content-Type'))
})

/* app.use(function (req, res, next) {
  // console.log(req)
  // req.testing = 'testing'
  // 在这里验证token
  console.log(new Date().toISOString(), ' ', 'Authorization:', req.get('Authorization'))
  console.log('res Content-Type:', req.get('Content-Type'))
  const token = req.get('Authorization')
  if (token === '1111') {
    return next()
  } else {
    res.status(403)
  }
  // console.log(res.header('Content-Type'))

  //   if(req.get('content-type').indexOf ('application/json')>=0){
  // console.log(req.path,'==>',res)
  //   }
  // 添加一个自定义函数可用
  // res.ok = res.json
  return next()
}) */

const routerInit = require('./router/index')
// 获取所有路由
routerInit(app)
const swagger = require('./config/swagger')
swagger(app, 8081)
const env = process.env.NODE_ENV
const server = app.listen(8081, function () {
  if (env === 'env') {
    swagger(app, 8081)
  }
  const host = server.address().address
  const port = server.address().port
  console.log('应用实例，访问地址为 http://%s:%s', host, port)
})

/* utf8、ucs2、ascii、binary、base64、hex */
/* fs.readFile("./src/xue1.pfx","base64",(err,data)=>{
  console.log(err?err:data)
}) */
